package hu.jonas.allunit.nature;

import hu.jonas.allunit.builder.AllUnitProjectBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

public class AllUnitNature implements IProjectNature {

	public static final String ID = "hu.jonas.allunit.allUnitNature"; 
	
	private IProject project;
	
	@Override
	public void configure() throws CoreException {
		IProjectDescription description = project.getDescription();
		
		ICommand[] buildSpec = description.getBuildSpec();
		ICommand[] newBuilders = Arrays.copyOf(buildSpec, buildSpec.length + 1);

		ICommand allUnitBuilder = description.newCommand();
		allUnitBuilder.setBuilderName(AllUnitProjectBuilder.ID);
		
		newBuilders[newBuilders.length - 1] = allUnitBuilder;
		
		description.setBuildSpec(newBuilders);
		project.setDescription(description, null);
	}

	@Override
	public void deconfigure() throws CoreException {
		IProjectDescription description = project.getDescription();
		ICommand[] buildSpec = description.getBuildSpec();
		
		List<ICommand> newBuilders = new ArrayList<ICommand>();
		for (int i = 0; i < buildSpec.length; i++) {
			if (!buildSpec[i].getBuilderName().equals(AllUnitProjectBuilder.ID)) {
				newBuilders.add(buildSpec[i]);
			}
		}
		
		description.setBuildSpec(newBuilders.toArray(new ICommand[0]));
		project.setDescription(description, null);
	}

	@Override
	public IProject getProject() {
		return project;
	}

	@Override
	public void setProject(IProject project) {
		this.project = project;
	}

}
